package com.hoapital.outpbillwork.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoapital.outpbillwork.module.controller.vo.ApplyInfo;
import com.hoapital.outpbillwork.module.controller.vo.ItemData;
import com.hoapital.outpbillwork.module.controller.vo.OrderInfo;
import com.hospital.common.core.exception.ExceptionHelp;
import com.hospital.common.core.exception.ExceptionHelpEnum;
import com.hospital.common.core.function.PushMessage;
import com.hospital.common.core.hl7Model.hospitalWork.BATCH;
import com.hospital.common.core.hl7Model.hospitalWork.LabHl7;
import com.hospital.common.core.hl7Model.hospitalWork.LabHl7Order;
import com.hospital.common.core.hl7Model.messages.*;
import com.hospital.common.core.hl7Model.segments.OML_O21;
import com.hoapital.outpbillwork.function.setValue.SetLabHl7Value;
import com.hoapital.outpbillwork.module.controller.vo.*;
import com.hoapital.outpbillwork.module.entity.*;
import com.hoapital.outpbillwork.module.mapper.*;
import com.hoapital.outpbillwork.module.service.DrugPrescMasterService;
import com.hoapital.outpbillwork.module.service.LabTestMasterService;
import com.hoapital.outpbillwork.module.service.OutpOrderDescService;
import com.hospital.common.core.module.controller.vo.*;
import com.hospital.common.core.utils.DateUtil;
import com.hospital.common.core.utils.XMLUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lvyao
 * @since 2021-02-25
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class LabTestMasterServiceImpl extends ServiceImpl<LabTestMasterMapper, LabTestMaster> implements LabTestMasterService {
    @Resource
    private LabTestMasterMapper labTestMasterMapper;

    @Resource
    private LabTestItemsMapper labTestItemsMapper;

    @Resource
    private DrugPrescMasterService drugPrescMasterService;

    @Resource
    private PatientInfoMapper patientInfoMapper;

    @Resource
    private ClinicItemDictMapper clinicItemDictMapper;
    @Resource
    private ClinicMasterMapper clinicMasterMapper;

    @Resource
    private OutpMedrecMapper outpMedrecMapper;

    @Resource
    private OutpBillItemsTempMapper outpBillItemsTempMapper;

    @Resource
    private OutpDoctorAssistantMapper outpDoctorAssistantMapper;

    @Resource
    private OutpOrderDescTempMapper outpOrderDescTempMapper;

    @Resource
    private AppConfigerBaseinfoMapper appConfigerBaseinfoMapper;

    @Resource
    private PushMessage pushMessage;

    @Resource
    private OutpOrderDescService outpOrderDescService;

    @Resource
    private OutpPrepayRcptTempMapper outpPrepayRcptTempMapper;

    @Resource
    private OrderVsBillnoMapper orderVsBillnoMapper;

    @Override
    public int updateChargeFlag(String testNo) {
        return labTestMasterMapper.updateChargeFlag(testNo);
    }

    @Override
    public String getTestNo(String visitDate, String visitNo) {
        return labTestMasterMapper.getTestNo(visitDate, visitNo);
    }

    @Override
    public boolean saveBillLab(Receive receive) throws ParseException {
        String testNo = labTestMasterMapper.getTestNo(receive.getPrimaryDate(), receive.getPrimaryNo()) == null ? receive.getApplyNo() : labTestMasterMapper.getTestNo(receive.getPrimaryDate(), receive.getPrimaryNo());
        if (testNo != null) {
            QueryWrapper<LabTestItems> labTestItemsEntityWrapper = new QueryWrapper<>();
            labTestItemsEntityWrapper.eq("test_no", testNo);
            List<LabTestItems> labTestItemsList = labTestItemsMapper.selectList(labTestItemsEntityWrapper);
            List<ReceiveDate> receiveDateList = receive.getData();
            if (labTestItemsList != null && !labTestItemsList.isEmpty() && labTestItemsList != null && !labTestItemsList.isEmpty()) {
                for (ReceiveDate receiveDate : receiveDateList) {
                    //更新单个检验项目收费标记
                    int updateChargeFlag1 = labTestItemsMapper.updateChargeFlag(testNo, receiveDate.getItemCode());
                    if (updateChargeFlag1 <= 0) {
                        throw new ExceptionHelp(ExceptionHelpEnum.UPDATE_ITEM_BILL_CHARGE_FLAG);
                    }
                }
                //所有项目收费标记都完成了再更新主表收费标记
                int testNoAllItemChargeFlag = labTestItemsMapper.getTestNoAllItemChargeFlag(testNo);
                if (testNoAllItemChargeFlag == 0) {
                    int updateChargeFlag = labTestMasterMapper.updateChargeFlag(testNo);
                    if (updateChargeFlag <= 0) {
                        throw new ExceptionHelp(ExceptionHelpEnum.UPDATE_ITEM_BILL_CHARGE_FLAG);
                    }
                }
                //处理门诊医嘱主表，删除门诊医嘱临时表，删除门诊计费临时表，插入住院计费，插入门诊计费表 --新增判断若无任务分类按集中模式处理标记
                if (!(receive.getTaskId() == null) && !receive.getTaskId().equals("")) {
                    boolean commBill = drugPrescMasterService.commBill(receive, labTestMasterMapper.selectById(testNo).getPatientId(), String.valueOf(labTestMasterMapper.selectById(testNo).getVisitId()), labTestMasterMapper.selectById(testNo).getOrderingDept());
                    if (!commBill) {
                        throw new ExceptionHelp(ExceptionHelpEnum.COMMBILL);
                    }
                }
                return true;
            } else {
                throw new ExceptionHelp(ExceptionHelpEnum.REQ_INFOR_ERRE);
            }
        } else {
            throw new ExceptionHelp(ExceptionHelpEnum.REQ_INFOR_NULL);
        }
    }

    @Override
    public Map<String, String> saveOrderLab(OrderInfo orderInfo) throws ExceptionHelp {
        //从入参中获取患者ID
        PatientInfo patInfo = orderInfo.getPatInfo();
        //从入参中获取患者申请医嘱信息
        List<ApplyInfo> applyInfoList = orderInfo.getApplyInfo();
        //从入参中获取患者诊断信息
        List<DiagnosisInfo> diagnosisDetailList = orderInfo.getDiagnosis();
        //从主索引信息获取患者全部信息
        PatientInfo patientInfo = patientInfoMapper.selectById(patInfo.getPatientId());
        //检查入参中数据是否给足
        ExceptionHelp exceptionHelp = checkOrder(patInfo, applyInfoList, diagnosisDetailList, patientInfo);
        if (exceptionHelp != null) {
            throw exceptionHelp;
        }
        int age = DateUtil.getAge(patientInfo.getDateOfBirth());
        Timestamp visitDate = new Timestamp(System.currentTimeMillis());
        int visitNo = Integer.parseInt(labTestMasterMapper.getVisitNo());
        int outpId = labTestMasterMapper.getOutpIdOld(patientInfo.getPatientId());
        String visitTime = DateUtil.format(visitDate, "HH:mm");

        //组装门诊挂号记录
        ClinicMaster clinicMaster = new ClinicMaster();
        clinicMaster.setPatientId(patientInfo.getPatientId());
        clinicMaster.setVisitDate(visitDate);
        clinicMaster.setVisitNo(visitNo);
        clinicMaster.setPayWay("1");
        clinicMaster.setRegistFee(new BigDecimal(0));
        clinicMaster.setClinicFee(new BigDecimal(0));
        clinicMaster.setClinicCharge(new BigDecimal(0));
        clinicMaster.setOtherFee(new BigDecimal(0));
        clinicMaster.setOutpId(outpId);
        clinicMaster.setName(patientInfo.getName());
        clinicMaster.setNamePhonetic(patientInfo.getNamePhonetic());
        clinicMaster.setSex(patientInfo.getSex());
        clinicMaster.setAge(age);
        clinicMaster.setIdentity(patientInfo.getIdentity());
        clinicMaster.setChargeType(patientInfo.getChargeType());
        clinicMaster.setUnitInContract(patientInfo.getUnitInContract());
        clinicMaster.setClinicType(diagnosisDetailList.get(0).getClinicType());
        clinicMaster.setVisitDept(diagnosisDetailList.get(0).getDiagDept());
        clinicMaster.setDoctor(diagnosisDetailList.get(0).getDiagDoctor());
        clinicMaster.setRegistrationStatus(3);
        clinicMaster.setRegisteringDate(visitDate);
        clinicMaster.setOperator(diagnosisDetailList.get(0).getDiagDoctor());
        clinicMaster.setDoctor(diagnosisDetailList.get(0).getDiagDoctor());
        clinicMaster.setDoctorId(diagnosisDetailList.get(0).getDiagDoctorId());
        clinicMaster.setFirstVisitIndicator(Integer.parseInt(diagnosisDetailList.get(0).getFirstVisitIndicator()));
        //组装交易订单记录
        OutpPrepayRcptTemp outpPrepayRcptTemp = new OutpPrepayRcptTemp();
        outpPrepayRcptTemp.setPatientId(patientInfo.getPatientId());
        String orderNumber = UUID.randomUUID().toString().replace("-", "");
        String guid = labTestMasterMapper.getGuid();
        BigDecimal allapplyCharges = new BigDecimal("0");
        outpPrepayRcptTemp.setGuid(guid);
        outpPrepayRcptTemp.setOrderNo(orderNumber);
        outpPrepayRcptTemp.setInpOrOutp(String.valueOf(Integer.parseInt(orderInfo.getOutpOrInp())));
        outpPrepayRcptTemp.setReturnAmount(new BigDecimal("0"));
        String CompanyFlag = "微信";
        outpPrepayRcptTemp.setTransactType("结算");
        outpPrepayRcptTemp.setSettleFlag("1");
        outpPrepayRcptTemp.setHisTransactDate(Timestamp.valueOf(DateUtil.getTime()));
        outpPrepayRcptTemp.setHisTranStatus("1");

        //初始化需要插入表的数据
        List<OutpOrderDescTemp> outpOrderDescTempList = new ArrayList<>();
        List<LabTestMaster> labTestMasterList = new ArrayList<>();
        List<OutpDoctorAssistant> outpDoctorAssistantList = new ArrayList<>();
        List<OutpBillItemsTemp> outpBillItemsTempList = new ArrayList<>();
        List<LabTestItems> labTestItemsList = new ArrayList<>();
        List<OrderVsBillno> orderVsBillnoList = new ArrayList<>();

        //循环医嘱申请消息
        for (ApplyInfo applyInfo : applyInfoList) {
            //查看患者是否当天重复申请做待 检测名字的项目
            QueryWrapper<LabTestMaster> labTestMasterQueryWrapper = new QueryWrapper<>();
            List<LabTestMaster> labTestMasters = labTestMasterMapper.selectList(labTestMasterQueryWrapper.apply("patient_id = {0} and  " +
                            "test_no = {1} ",
                    orderInfo.getPatInfo().getPatientId(), applyInfo.getOrder().getOrderNo()));
            if (labTestMasters != null && !labTestMasters.isEmpty() && labTestMasters.size() > 0) {
                throw new ExceptionHelp(ExceptionHelpEnum.LAB_CHECK_RETR_ORDER);
            }
            //医嘱信息
            OrderContent order = applyInfo.getOrder();
            String tsStr = order.getOrderDate().replace("/", "-");
            visitDate = Timestamp.valueOf(tsStr);
            visitNo = Integer.parseInt(labTestMasterMapper.getVisitNo());
            String testNoDual = labTestMasterMapper.getTestNoDual();
            String orderNo = order.getOrderNo();
            String testNo = orderNo == null || orderNo.equals("") ? DateUtil.format(visitDate, "yyMMdd") + String.format("%06d", Integer.parseInt(testNoDual)) : order.getOrderNo();
            OutpOrderDescTemp outpOrderDescTemp = new OutpOrderDescTemp();
            outpOrderDescTemp.setVisitDate(visitDate);
            outpOrderDescTemp.setVisitNo(visitNo);
            outpOrderDescTemp.setPatientId(patientInfo.getPatientId());
            outpOrderDescTemp.setOrderedByDept(order.getOrderedByDept());
            outpOrderDescTemp.setOrderedByDoctor(order.getOrderedByDoctor());
            outpOrderDescTemp.setPrescIndicator(0);
            outpOrderDescTemp.setOutpId(outpId);
            outpOrderDescTemp.setOrderNo(testNo);
            outpOrderDescTemp.setOrderType(order.getOrderType());
            outpOrderDescTemp.setUserId(order.getUserId());
            //将需要插入表的临时医嘱信息放到List
            outpOrderDescTempList.add(outpOrderDescTemp);

            //交易订单明细表
            OrderVsBillno orderVsBillno = new OrderVsBillno();
            orderVsBillno.setOrderNo(orderNumber);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String billNumber = df.format(visitDate) + visitNo;
            orderVsBillno.setBillNo(billNumber);
            orderVsBillnoList.add(orderVsBillno);

            //组装检验主记录信息
            LabTestMaster labTestMaster = new LabTestMaster();
            labTestMaster.setTestNo(testNo);
            labTestMaster.setPriorityIndicator(0);
            labTestMaster.setPatientId(patientInfo.getPatientId());
            labTestMaster.setName(patientInfo.getName());
            labTestMaster.setNamePhonetic(patientInfo.getNamePhonetic());
            labTestMaster.setChargeType(patientInfo.getChargeType());
            labTestMaster.setSex(patientInfo.getSex());
            labTestMaster.setAge(age);
            labTestMaster.setTestCause(orderInfo.getOutpOrInp().equals("01") ? "门诊" : "住院");
            labTestMaster.setRelevantClinicDiag(diagnosisDetailList.get(0).getDiagName());
            labTestMaster.setSpecimen(order.getSpecimen());
            labTestMaster.setRequestedDateTime(visitDate);
            labTestMaster.setOrderingDept(order.getOrderedByDept());
            labTestMaster.setOrderingProvider(order.getOrderedByDoctor());
            labTestMaster.setPerformedBy(order.getPerformedBy());
            labTestMaster.setResultStatus("A");
            labTestMaster.setBillingIndicator(0);

            //医嘱项目信息
            List<ItemData> itemDataList = applyInfo.getItemData();

            labTestMaster.setSubject(StringUtils.join(itemDataList.stream().map(ItemData::getItemName).collect(Collectors.toList()), "+"));
            BigDecimal allCosts = new BigDecimal("0");
            BigDecimal allCharges = new BigDecimal("0");
            //循环获取医嘱项目具体信息
            for (ItemData itemData : itemDataList) {
                //查询医嘱项目具体信息
                QueryWrapper<ClinicItemDict> clinicItemDictQueryWrapper = new QueryWrapper<>();
                String category = orderInfo.getOutpOrInp().equals("01") ? "门诊" : "住院";
                clinicItemDictQueryWrapper.apply(" item_class = {0}\n" +
                        "   And Category Like '%" + category + "%'\n" +
                        "   And rank Is Not Null\n" +
                        "   And (is_using <> '停用' or is_using is null)\n" +
                        "   And item_code = {1}", itemData.getItemClass(), itemData.getItemCode());
                List<ClinicItemDict> clinicItemDictList = clinicItemDictMapper.selectList(clinicItemDictQueryWrapper);
                if (clinicItemDictList.isEmpty() || clinicItemDictList.size() > 1) {
                    throw new ExceptionHelp(ExceptionHelpEnum.LAB_ORDER_BILLINFO);
                }
                BigDecimal itemCosts = new BigDecimal("0");
                BigDecimal itemCharges = new BigDecimal("0");
                //查询医嘱收费项目明细
                List<ClinicItemBill> clinicItemBillList = labTestMasterMapper.getBillList(itemData.getItemCode(),itemData.getItemSpec());
                if (clinicItemBillList.isEmpty()) {
                    throw new ExceptionHelp(ExceptionHelpEnum.LAB_ORDER_BILLITEMS);
                }
                //组装检验明细项目
                LabTestItems labTestItems = new LabTestItems();
                labTestItems.setTestNo(testNo);
                labTestItems.setItemNo(itemDataList.indexOf(itemData) + 1);
                labTestItems.setItemCode(clinicItemDictList.get(0).getItemCode());
                labTestItems.setItemName(clinicItemDictList.get(0).getItemName());
                labTestItems.setResultStatus("A");
                //组装门诊处置表
                OutpDoctorAssistant outpDoctorAssistant = new OutpDoctorAssistant();
                outpDoctorAssistant.setPatientId(patientInfo.getPatientId());
                outpDoctorAssistant.setOutpId(outpId);
                outpDoctorAssistant.setVisitDate(visitDate);
                outpDoctorAssistant.setVisitTime(visitTime);
                outpDoctorAssistant.setVisitNo(visitNo);
                outpDoctorAssistant.setItemNo(itemDataList.indexOf(itemData) + 1);
                outpDoctorAssistant.setItemClass(clinicItemDictList.get(0).getItemClass());
                outpDoctorAssistant.setItemCode(clinicItemDictList.get(0).getItemCode());
                outpDoctorAssistant.setItemName(clinicItemDictList.get(0).getItemName());
                outpDoctorAssistant.setPerformedBy(clinicItemDictList.get(0).getPerformedBy());
                outpDoctorAssistant.setIds(testNo);
                outpDoctorAssistant.setDept(order.getOrderedByDept());
                outpDoctorAssistant.setDoctor(order.getOrderedByDoctor());
                outpDoctorAssistant.setChargeFlag(0);
                outpDoctorAssistant.setAmount(itemData.getAmount());
                //循环获取医嘱计费信息
                for (ClinicItemBill clinicItemBill : clinicItemBillList) {
//                    BigDecimal charges = clinicItemBill.getPrice().multiply(clinicItemBill.getAmount()).multiply(itemData.getAmount());
                    //组装门诊临时收费信息
                    OutpBillItemsTemp outpBillItemsTemp = new OutpBillItemsTemp();
                    outpBillItemsTemp.setVisitDate(visitDate);
                    outpBillItemsTemp.setVisitNo(visitNo);
                    outpBillItemsTemp.setItemNo(outpBillItemsTempList.size() + 1);
                    outpBillItemsTemp.setItemClass(clinicItemBill.getItemClass());
                    outpBillItemsTemp.setClassOnRcpt(clinicItemBill.getClassOnInpRcpt());
                    outpBillItemsTemp.setItemCode(clinicItemBill.getItemCode());
                    outpBillItemsTemp.setItemName(clinicItemBill.getItemName());
                    outpBillItemsTemp.setItemSpec(clinicItemBill.getItemSpec());
                    outpBillItemsTemp.setAmount(clinicItemBill.getAmount().multiply(itemData.getAmount()));
                    outpBillItemsTemp.setUnits(clinicItemBill.getUnits());
                    outpBillItemsTemp.setPerformedBy(itemData.getPerformedBy());
                    if (itemData.getCosts() == null || itemData.getCharges() == null) {
                        throw new ExceptionHelp(ExceptionHelpEnum.ITEM_NULL_COSTS);
                    }
                    outpBillItemsTemp.setCosts(itemData.getCosts());
                    outpBillItemsTemp.setCharges(itemData.getCharges());
                    itemCosts = itemCosts.add(itemData.getCosts());
                    itemCharges = itemCharges.add(itemData.getCharges());
                    //将需要插入表的临时收费信息放到List
                    outpBillItemsTempList.add(outpBillItemsTemp);
                }
                outpDoctorAssistant.setCosts(itemCosts);
                outpDoctorAssistant.setCharges(itemCharges);
                labTestItems.setPrice(itemCosts);
                allCosts = allCosts.add(itemCosts);
                allCharges = allCharges.add(itemCharges);
                //将需要插入表的检验明细项目信息放到List
                labTestItemsList.add(labTestItems);
                //将需要插入表的门诊处置表信息放到List
                outpDoctorAssistantList.add(outpDoctorAssistant);
            }
            labTestMaster.setCosts(allCosts);
            labTestMaster.setCharges(allCharges);
            labTestMaster.setVisitNo(visitNo);
            labTestMaster.setVisitDate(visitDate);
            labTestMaster.setStatus("1");
            labTestMaster.setUserId("0000");
            labTestMaster.setGreenFlag("0");
            CompanyFlag = order.getCompanyFlag();
            labTestMaster.setCompanyFlag(CompanyFlag);
            //将需要插入表的检验信息放到List
            labTestMasterList.add(labTestMaster);
            allapplyCharges.add(allCharges);
        }

        outpPrepayRcptTemp.setPayWay(CompanyFlag);

        outpPrepayRcptTemp.setAmount(allapplyCharges);
        OutpMedrec outpMedrec = new OutpMedrec();
        //循环诊断信息
        for (DiagnosisInfo diagnosisDetail : diagnosisDetailList) {
            //组装门诊诊断信息
            outpMedrec.setVisitDate(visitDate);
            outpMedrec.setPatientId(patientInfo.getPatientId());
            outpMedrec.setOutpId(outpId);
            outpMedrec.setVisitTime(visitTime);
            outpMedrec.setDept(diagnosisDetail.getDiagDept());
            outpMedrec.setDoctor(diagnosisDetail.getDiagDoctor());
            outpMedrec.setNotes(diagnosisDetail.getNotes());
            outpMedrec.setPatientCondition(diagnosisDetail.getPatientCondition());
            outpMedrec.setResult(diagnosisDetail.getDiagName());
            outpMedrec.setSymptom(diagnosisDetail.getSymptom());
            outpMedrec.setPhysical(diagnosisDetail.getPhysical());
            outpMedrec.setPresentIllness(diagnosisDetail.getPresentIllness());
            outpMedrec.setPastIllness(diagnosisDetail.getPastIllness());
            outpMedrec.setAuxExamResults(diagnosisDetail.getAuxExamResults());
            outpMedrec.setDiagCode(diagnosisDetail.getDiagCode());
        }
//        BATCH getHl7LabMessage = SetFunctionHL7.packageOmallMessage(outpMedrec, outpOrderDescTempList, Collections.singletonList(labTestMasterList),
//                Collections.singletonList(labTestItemsList), orderInfo.getHospitalCode(),orderInfo.getHospitalName(),orderInfo.getOutpOrInp(), patientInfo
//                , AllFinalValueUtils.ORC_1_NEW, AllFinalValueUtils.ORC_5_NEW,labTestMasterMapper,AllFinalValueUtils.TEST );
        BATCH getHl7LabMessage = getHl7Message(outpMedrec, outpOrderDescTempList, labTestMasterList, labTestItemsList, orderInfo.getHospitalCode(), orderInfo.getHospitalName(), orderInfo.getOutpOrInp(), patientInfo);
        //直接存为xml文件 中间多节点 labHl7Orders
        String convertToXml = XMLUtil.convertToXml(getHl7LabMessage).replace("<labHl7Orders>", "").replace("</labHl7Orders>", "").replace("UTF-8", "UTF8");
        QueryWrapper<AppConfigerBaseinfo> appConfigerBaseinfoQueryWrapper1 = new QueryWrapper<>();
        appConfigerBaseinfoQueryWrapper1.eq("app_name", "*");
        List<AppConfigerBaseinfo> appConfigerBaseinfoList = appConfigerBaseinfoMapper.selectList(appConfigerBaseinfoQueryWrapper1);
        //XML_HL7_FILE  XML_HL7_URL  WX_HL7_POST_URL
        String filePath = null;
        String postHl7Url = null;
        String xmlHl7Url = null;
        try {
            filePath = appConfigerBaseinfoList.stream().filter(appConfigerBaseinfo -> appConfigerBaseinfo.getParameterName().equals("XML_HL7_FILE")).collect(Collectors.toList()).get(0).getParainitValue();
            postHl7Url = appConfigerBaseinfoList.stream().filter(appConfigerBaseinfo -> appConfigerBaseinfo.getParameterName().equals("WX_HL7_POST_URL")).collect(Collectors.toList()).get(0).getParainitValue();
            xmlHl7Url = appConfigerBaseinfoList.stream().filter(appConfigerBaseinfo -> appConfigerBaseinfo.getParameterName().equals("XML_HL7_URL")).collect(Collectors.toList()).get(0).getParainitValue();
        } catch (Exception e) {
            throw new ExceptionHelp(ExceptionHelpEnum.GET_HL7_CONFIGER_ERR);
        }
        //获取计费单号存储对应文件
//        String billNo = null;
//        for (OutpOrderDescTemp outpOrderDescTemp : outpOrderDescTempList) {
//            billNo += new SimpleDateFormat("yyyyMMddHHmmss").format(outpOrderDescTemp.getVisitDate()) + outpOrderDescTemp.getVisitNo();
//            if (outpOrderDescTempList.indexOf(outpOrderDescTemp) != outpOrderDescTempList.size() - 1) {
//                billNo += ",";
//            }
//        }
        String replace = orderNumber.replace("null", "");
        filePath += replace + ".xml";
        boolean string2File = XMLUtil.string2File(convertToXml, filePath);
        if (!string2File) {
            throw new ExceptionHelp(ExceptionHelpEnum.HL7_XMLFILE_FILDS);
        }

        //推送申请
        pushMessage.sendLabApplyInfo(orderInfo.getHospitalCode(), orderInfo.getHospitalName(), xmlHl7Url, filePath, postHl7Url, "0");
        //更新表数据
        Map<String, String> map = updateAllTab(clinicMaster, outpMedrec, outpOrderDescTempList, outpBillItemsTempList, outpDoctorAssistantList, labTestMasterList, labTestItemsList, outpPrepayRcptTemp, orderVsBillnoList);
        map.put("billNo", replace);
        return map;
    }

    @Override
    public boolean cancelLab(CancelOrder cancelOrder) throws ExceptionHelp {
        //推送申请撤销消息到检验
        String billNos = cancelOrder.getBillNo();
        QueryWrapper<OrderVsBillno> orderVsBillnoQueryWrapper = new QueryWrapper<>();
        orderVsBillnoQueryWrapper.eq("order_no", billNos);
        List<OrderVsBillno> orderVsBillnoList = orderVsBillnoMapper.selectList(orderVsBillnoQueryWrapper);
        String collect = orderVsBillnoList.stream().map(p -> p.getBillNo()).collect(Collectors.joining(","));
        String[] billNoList = collect.split(",");
        if (billNoList.length == 0) {
            throw new ExceptionHelp(ExceptionHelpEnum.ANCEL_ORDER_LAB_BILLNO);
        }
        String filePath;
        String postHl7Url;
        String xmlHl7Url;
        QueryWrapper<AppConfigerBaseinfo> appConfigerBaseinfoQueryWrapper1 = new QueryWrapper<>();
        appConfigerBaseinfoQueryWrapper1.eq("app_name", "*");
        List<AppConfigerBaseinfo> appConfigerBaseinfoList = appConfigerBaseinfoMapper.selectList(appConfigerBaseinfoQueryWrapper1);
        try {
            filePath = appConfigerBaseinfoList.stream().filter(appConfigerBaseinfo1 -> appConfigerBaseinfo1.getParameterName().equals("XML_HL7_FILE")).collect(Collectors.toList()).get(0).getParainitValue();
            postHl7Url = appConfigerBaseinfoList.stream().filter(appConfigerBaseinfo1 -> appConfigerBaseinfo1.getParameterName().equals("WX_HL7_POST_URL")).collect(Collectors.toList()).get(0).getParainitValue();
            xmlHl7Url = appConfigerBaseinfoList.stream().filter(appConfigerBaseinfo1 -> appConfigerBaseinfo1.getParameterName().equals("XML_HL7_URL")).collect(Collectors.toList()).get(0).getParainitValue();
        } catch (Exception e) {
            ExceptionHelp exceptionHelp = new ExceptionHelp(ExceptionHelpEnum.GET_HL7_CONFIGER_ERR);
            log.info(billNos + ":" + exceptionHelp);
            return false;
        }
        for (String billno : billNoList) {
            QueryWrapper<LabTestMaster> queryWrapper1 = new QueryWrapper<>();
            LabTestMaster labTestMaster;
            try {
                labTestMaster = (LabTestMaster) outpOrderDescService.getList(queryWrapper1, billno, LabTestMaster.class).get(0);
            } catch (Exception e) {
                throw new ExceptionHelp(ExceptionHelpEnum.CANCEL_ORDER_LAB_INFOR);
            }
            Integer billingIndicator = labTestMaster.getBillingIndicator();
            if (billingIndicator == 1) {
                throw new ExceptionHelp(ExceptionHelpEnum.CANCEL_ORDER_BILL);
            }
            if (!labTestMaster.getResultStatus().equals("A")) {
                throw new ExceptionHelp(ExceptionHelpEnum.CANCEL_ORDER_STATUS);
            }
            int integer = labTestMasterMapper.updateStatus(labTestMaster.getTestNo());
            if (integer < 0) {
                throw new ExceptionHelp(ExceptionHelpEnum.CANCEL_ORDER_LAB_STATUS);
            }
            int updateChanceFlag = outpDoctorAssistantMapper.updateChanceFlag(billno.substring(0, 14), billno.substring(14));
            if (updateChanceFlag < 0) {
                throw new ExceptionHelp(ExceptionHelpEnum.CANCEL_ORDER_ASS_STATUS);
            }
            int updateChanceFlag1 = labTestItemsMapper.updateChanceFlag(labTestMaster.getTestNo());
            if (updateChanceFlag1 < 0) {
                throw new ExceptionHelp(ExceptionHelpEnum.CANCEL_ORDER_LAB_DETAIL_STATUS);
            }
            String filePathCancel = filePath + billNos + ".xml";
            pushMessage.sendLabApplyInfo(cancelOrder.getHospitalCode(), cancelOrder.getHospitalName(), xmlHl7Url, filePathCancel, postHl7Url, "2");
//            pushMessage.sendLabBillInfo("OML_O21", cancelOrder.getHospitalCode(), cancelOrder.getHospitalName(), xmlHl7Url, filePathCancel, postHl7Url, "2");
        }
        return true;
    }


    /**
     * 检查入参中信息是否充足
     *
     * @param patInfo             入参的患者基本信息
     * @param applyInfoList       医嘱申请消息
     * @param diagnosisDetailList 诊断消息
     * @param patientInfo         查表获取的患者基本信息
     * @return
     */
    public ExceptionHelp checkOrder(PatientInfo patInfo, List<ApplyInfo> applyInfoList, List<DiagnosisInfo> diagnosisDetailList, PatientInfo patientInfo) {
        if (patInfo == null) {
            return new ExceptionHelp(ExceptionHelpEnum.LAB_ORDER_INP_PAT);
        }
        if (applyInfoList.isEmpty()) {
            return new ExceptionHelp(ExceptionHelpEnum.LAB_ORDER_INP_ORDER);
        }
        if (diagnosisDetailList.isEmpty() || diagnosisDetailList.size() > 1) {
            if (diagnosisDetailList.get(0).getClinicType() == null || diagnosisDetailList.get(0).getClinicType().trim().equals("") ||
                    diagnosisDetailList.get(0).getDiagDept() == null || diagnosisDetailList.get(0).getDiagDept().trim().equals("") ||
                    diagnosisDetailList.get(0).getDiagDoctor() == null || diagnosisDetailList.get(0).getDiagDoctor().trim().equals("") ||
                    diagnosisDetailList.get(0).getDiagDoctor() == null || diagnosisDetailList.get(0).getDiagDoctor().trim().equals("") ||
                    diagnosisDetailList.get(0).getDiagDoctor() == null || diagnosisDetailList.get(0).getDiagDoctor().trim().equals("") ||
                    diagnosisDetailList.get(0).getDiagDoctorId() == null || diagnosisDetailList.get(0).getDiagDoctorId().trim().equals("") ||
                    diagnosisDetailList.get(0).getFirstVisitIndicator() == null || diagnosisDetailList.get(0).getFirstVisitIndicator().trim().equals("")) {
                return new ExceptionHelp(ExceptionHelpEnum.DIAG_ERR_FILDS);
            }
            return new ExceptionHelp(ExceptionHelpEnum.LAB_ORDER_INP_DIAG);
        }
        if (patientInfo == null) {
            return new ExceptionHelp(ExceptionHelpEnum.LAB_ORDER_INP_PATTABLE);
        }
        return null;
    }

    public Map<String, String> updateAllTab(ClinicMaster clinicMaster, OutpMedrec outpMedrec,
                                            List<OutpOrderDescTemp> outpOrderDescTempList,
                                            List<OutpBillItemsTemp> outpBillItemsTempList,
                                            List<OutpDoctorAssistant> outpDoctorAssistantList,
                                            List<LabTestMaster> labTestMasterList,
                                            List<LabTestItems> labTestItemsList,
                                            OutpPrepayRcptTemp outpPrepayRcptTemp,
                                            List<OrderVsBillno> orderVsBillnoList) {

        Map<String, String> map = new HashMap<>();
        Integer insert = clinicMasterMapper.insert(clinicMaster);
        if (!(insert >= 1)) {
            throw new ExceptionHelp(ExceptionHelpEnum.CLINIC_MASTER_INSERT);
        }
        Integer insertRec = outpPrepayRcptTempMapper.insert(outpPrepayRcptTemp);
        if (!(insertRec >= 1)) {
            throw new ExceptionHelp(ExceptionHelpEnum.OUTP_PREPAY_RCPT_TEMP_INSERT);
        }
        Integer insert1 = outpMedrecMapper.insert(outpMedrec);
        if (!(insert1 >= 1)) {
            throw new ExceptionHelp(ExceptionHelpEnum.OUTP_MEDREC_INSERT);
        }
        for (OutpOrderDescTemp outpOrderDescTemp : outpOrderDescTempList) {
            Integer insert2 = outpOrderDescTempMapper.insert(outpOrderDescTemp);
            if (!(insert2 >= 1)) {
                throw new ExceptionHelp(ExceptionHelpEnum.OUTP_ORDER_DESC_TEMP_INSERT);
            }
        }
        for (OrderVsBillno orderVsBillno : orderVsBillnoList) {
            Integer insert2 = orderVsBillnoMapper.insert(orderVsBillno);
            if (!(insert2 >= 1)) {
                throw new ExceptionHelp(ExceptionHelpEnum.OUTP_PREPAY_RCPT_VS_BILL_INSERT);
            }
        }
        for (OutpBillItemsTemp outpBillItemsTemp : outpBillItemsTempList) {
            Integer insert2 = outpBillItemsTempMapper.insert(outpBillItemsTemp);
            if (!(insert2 >= 1)) {
                throw new ExceptionHelp(ExceptionHelpEnum.OUTP_BILL_ITEMS_TEMP_INSERT);
            }
        }
        for (OutpDoctorAssistant outpDoctorAssistant : outpDoctorAssistantList) {
            Integer insert2 = outpDoctorAssistantMapper.insert(outpDoctorAssistant);
            if (!(insert2 >= 1)) {
                throw new ExceptionHelp(ExceptionHelpEnum.OUTP_DOCTOR_ASSISTANT_INSERT);
            }
        }
        for (LabTestMaster labTestMaster : labTestMasterList) {
            Integer insert2 = labTestMasterMapper.insert(labTestMaster);
            if (!(insert2 >= 1)) {
                throw new ExceptionHelp(ExceptionHelpEnum.LAB_TEST_MASTER_INSERT);
            }
        }
        for (LabTestItems labTestItems : labTestItemsList) {
            Integer insert2 = labTestItemsMapper.insert(labTestItems);
            if (!(insert2 >= 1)) {
                throw new ExceptionHelp(ExceptionHelpEnum.LAB_TEST_ITEMS_INSERT);
            }
        }
        map.put("updateFlag", "true");
        return map;
    }

    public BATCH getHl7Message(OutpMedrec outpMedrec,
                               List<OutpOrderDescTemp> outpOrderDescTempList,
                               List<LabTestMaster> labTestMasterList,
                               List<LabTestItems> labTestItemsList, String hosCode, String hosName, String outpOrInp, PatientInfo patientInfo) {
        LabHl7 labHl7 = new LabHl7();
        BATCH batch = new BATCH();
        OML_O21 oml_o21 = new OML_O21();
        //给信息头
        MSH msh = SetLabHl7Value.getMsh("HTSoftWare", "LisSoftWare", "OML", "O21", hosCode, hosName, labTestMasterMapper.getGuid());
        oml_o21.setMSH(msh);
        //给患者基本信息
        patientInfo.setNationCode(labTestMasterMapper.getNationCode(patientInfo.getNation()));
        patientInfo.setCountryName(labTestMasterMapper.getCountryName(patientInfo.getCitizenship()));
        patientInfo.setBitthPlace(labTestMasterMapper.getBitthPlace(patientInfo.getBirthPlace()));
        PID pid = SetLabHl7Value.getPid(patientInfo);
        oml_o21.setPID(pid);

        //给患者住院信息
        PV1 pv1 = SetLabHl7Value.getPV1(String.valueOf(outpMedrec.getOutpId()), outpOrInp, "", "", ""
                , "", "", outpMedrec.getDocNo(), outpMedrec.getDoctor(), "", "", ""
                , "", "", "", "", ""
                , "","");
        oml_o21.setPV1(pv1);

        List<LabHl7Order> labHl7OrderList = new ArrayList<>();
        //给检验主记录信息以及项目信息
        for (OutpOrderDescTemp outpOrderDescTemp : outpOrderDescTempList) {
            LabTestMaster labTestMaster = labTestMasterList.get(outpOrderDescTempList.indexOf(outpOrderDescTemp));
            LabHl7Order labHl7Order = new LabHl7Order();
            ORC orc = SetLabHl7Value.getORC(String.valueOf(outpOrderDescTemp.getVisitNo()), outpOrderDescTemp.getUserId(), outpOrderDescTemp.getOrderedByDoctor(),
                    outpOrderDescTemp.getOrderedByDept(), hosCode, hosName, new SimpleDateFormat("yyyyMMddHHmmss").format(outpMedrec.getVisitDate()), "NW", "SC");

            outpOrderDescTemp.setOrderedByDeptName(labTestMasterMapper.getDeptName(outpOrderDescTemp.getOrderedByDept()));
            labTestMaster.setPerformedByName(labTestMasterMapper.getDeptName(labTestMaster.getPerformedBy()));

            List<OBR> obrList = new ArrayList<>();
            for (LabTestItems labTestItems : labTestItemsList) {
                labTestItems.setItemNo(labTestItemsList.indexOf(labTestItems) + 1);
                labTestItems.setSubLabDept(labTestMasterMapper.getSubLabDept(labTestItems.getItemCode()) == null ? "" : labTestMasterMapper.getSubLabDept(labTestItems.getItemCode()));
                OBR obr = SetLabHl7Value.getOBR(labTestMaster, outpOrderDescTemp.getUserId(), outpOrderDescTemp.getOrderedByDoctor(),
                        outpOrderDescTemp.getOrderedByDept(), outpOrderDescTemp.getOrderedByDeptName(), labTestItems);
                obrList.add(obr);
            }
            labHl7Order.setORC(orc);
            labHl7Order.setOBR(obrList);
            labHl7OrderList.add(labHl7Order);
        }
        oml_o21.setLabHl7Orders(labHl7OrderList);
        //给诊断信息
        //给诊断信息
        DG1 dg1 = SetLabHl7Value.getDG1("", outpMedrec.getDiagCode(), outpMedrec.getResult(),
                outpMedrec.getPhysical(), new SimpleDateFormat("yyyyMMddHHmmss").format(outpMedrec.getVisitDate()),
                "", "", "", outpMedrec.getDoctor(), "", "", "", "",
                "", "", "", "", "");
        oml_o21.setDG1(dg1);

        batch.setOML_O21(oml_o21);
        labHl7.setBATCH(batch);
        return batch;
    }

}
